package com.getpebble.android.framework.notification.gmail;

import com.sun.mail.imap.IMAPSSLStore;
import com.sun.mail.imap.IMAPStore;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;
import javax.mail.Session;

public class OAuth2Authenticator {

    public static final class OAuth2Provider extends Provider {
        private static final long serialVersionUID = 1;

        public OAuth2Provider() {
            super("Google OAuth2 Provider", 1.0d, "Provides the XOAUTH2 SASL Mechanism");
            put("SaslClientFactory.XOAUTH2", OAuth2SaslClientFactory.class.getName());
        }
    }

    public static void initialize() {
        Security.addProvider(new OAuth2Provider());
    }

    public static IMAPStore connectToImap(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception {
        Properties props = new Properties();
        props.put("mail.imaps.sasl.enable", "true");
        props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
        props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
        Session session = Session.getInstance(props);
        session.setDebug(debug);
        IMAPSSLStore store = new IMAPSSLStore(session, null);
        String emptyPassword = "";
        store.connect(host, port, userEmail, "");
        return store;
    }
}
